import 'package:flutter/material.dart';
import 'package:im_module/common/GroupCommonType.dart';
import 'package:im_module/friend/ChooseContact.dart';
import 'package:im_module/info/UpdateNameWidget.dart';
import 'package:im_module/manager/ImChatManager.dart';
import 'package:im_module/provider/im_provider.dart';
import 'package:im_module/widget/AppBarBackground.dart';
import 'package:im_module/widget/ImHeadImageWidget.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member_full_info.dart';

class GroupInfoWidget extends StatefulWidget {
  late String groupId;
  late String groupName;

  GroupInfoWidget(this.groupId, this.groupName);

  @override
  _GroupInfoWidgetState createState() => _GroupInfoWidgetState();
}

class _GroupInfoWidgetState extends State<GroupInfoWidget> {
  List<String> _selectIds = List.empty(growable: true);
  List<String> _selectDeletes = List.empty(growable: true);
  List<V2TimGroupMemberFullInfo?> list = List.empty(growable: true);

  bool deleteFlag = false;
  bool isManager = false;

  String? groupName;

  @override
  void initState() {
    super.initState();
    groupName = widget.groupName;

    getALlMember();

    //判断是否是群主
    owjudge();
  }

  void setGroupName(String? newGroupName) {
    setState(() {
      groupName = newGroupName;
    });
  }

  ///判断是否是群主
  void owjudge() async {
    isManager = await ImChatManager()
        .checkMemberAuthor(widget.groupId, ImChatManager().currentUserid);
    setState(() {});
  }

  void getALlMember() {
    //获取群的全部成员
    ImChatManager().getGroupMember(
        widget.groupId, GroupCommonType.V2TIM_GROUP_MEMBER_FILTER_ALL);
  }

  @override
  Widget build(BuildContext context) {
    return AppBarBackground(
      child: Scaffold(
          appBar: AppBar(
            title: Text('聊天信息'),
            centerTitle: true,
          ),
          body: Container(
            color: Colors.white,
            child: Padding(
              padding: const EdgeInsets.only(left: 15, right: 15, bottom: 30),
              child: Column(
                children: [
                  Container(
                    width: double.infinity,
                    height: 45,
                    margin: EdgeInsets.symmetric(vertical: 10),
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Positioned(
                          child: Text("群名称"),
                          left: 0,
                        ),
                        Positioned(
                          child: GestureDetector(
                            onTap: () async {
                              if (isManager == false) {
                                return;
                              }
                              String? groupName = await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (ctx) => UpdateNameWidget(
                                          "${widget.groupId}",
                                          "${widget.groupName}")));

                              if (groupName != null) {
                                setGroupName(groupName);
                              }
                            },
                            child: Row(
                              children: [
                                Text("$groupName"),
                                Icon(
                                  Icons.arrow_forward_ios_rounded,
                                  size: 18,
                                )
                              ],
                            ),
                          ),
                          right: 0,
                        ),
                      ],
                    ),
                  ),
                  Divider(
                    height: .5,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text("群成员"),
                      AddRemoveMenuWidget(
                        isManager: isManager,
                        deleteFlag: deleteFlag,
                        addPressed: () async {
                          var result = await Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (_) {
                                return ChooseContactWidget(
                                  groupId: widget.groupId,
                                  groupNumber: _selectIds,
                                );
                              },
                            ),
                          );
                          if (result) {
                            getALlMember();
                          }
                        },
                        removePressed: () {
                          setState(() {
                            deleteFlag = true;
                          });
                        },
                        deletePressed: () async {
                          if (_selectDeletes.isEmpty) {
                            setState(() {
                              deleteFlag = false;
                              _selectDeletes.clear();
                            });
                            return;
                          }

                          ///移除人
                          bool result = await ImChatManager()
                              .kickGroupMember(widget.groupId, _selectDeletes);

                          if (result) {
                            Navigator.pop(context);
                          } else {
                            setState(() {
                              deleteFlag = false;
                              _selectDeletes.clear();
                            });
                          }
                        },
                      ),
                    ],
                  ),
                  Divider(),
                  Expanded(
                    child: Consumer<ImProvider>(
                      builder: (context, _provider, _) {
                        list = _provider.mGroupMembers;
                        _selectIds.clear();
                        list.forEach((element) {
                          if (element != null) {
                            _selectIds.add(element.userID);
                          }
                        });
                        return ListView.builder(
                            itemCount: list.length,
                            itemBuilder: (context, index) {
                              V2TimGroupMemberFullInfo? data = list[index];
                              if (deleteFlag) {
                                return CheckboxListTile(
                                  dense: false,
                                  contentPadding:
                                      EdgeInsets.symmetric(horizontal: 10.0),
                                  secondary: ImHeadImageWidget(
                                    "${data?.faceUrl}",
                                    width: 28,
                                    height: 28,
                                  ),
                                  title: Text("${data?.nickName}"),
                                  value: _selectDeletes.contains(data?.userID),
                                  onChanged: data?.userID ==
                                          ImChatManager().getUserId()
                                      ? null
                                      : (bool? flag) {
                                          setState(() {
                                            if (flag!) {
                                              _selectDeletes
                                                  .add("${data?.userID}");
                                            } else {
                                              _selectDeletes
                                                  .remove("${data?.userID}");
                                            }
                                          });
                                        },
                                );
                              } else {
                                return Container(
                                  height: 48,
                                  child: Row(
                                    children: [
                                      ImHeadImageWidget(
                                        "${data?.faceUrl}",
                                        width: 28,
                                        height: 28,
                                      ),
                                      SizedBox(
                                        width: 10,
                                      ),
                                      Text(
                                        "${data?.nickName}",
                                        style: TextStyle(
                                            fontSize: 16,
                                            color: Color(0xff333333)),
                                      )
                                    ],
                                  ),
                                );
                              }
                            });
                      },
                    ),
                  ),
                  ElevatedButton(
                      onPressed: () async {
                        bool value = false;

                        //如果是群
                        if (isManager) {
                          if (list.length != 1) {
                            V2TimGroupMemberFullInfo? _member = list[1];
                            if (_member != null) {
                              ImChatManager().transferGroupOwner(
                                  widget.groupId, _member.userID);
                            }
                          }
                        }
                        value = await ImChatManager().quitGroup(widget.groupId);
                        if (value) {
                          Navigator.pop(context, true);
                        }
                      },
                      style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.all(Color(0xffef4734))),
                      child: Container(
                          width: MediaQuery.of(context).size.width * 0.7,
                          alignment: Alignment.center,
                          //child: Text("${isManager ? "解散群聊" : "退出群聊"}"))),
                          child: Padding(
                            padding: const EdgeInsets.all(10),
                            child: Text("退出群聊"),
                          ))),
                ],
              ),
            ),
          )),
    );
  }
}

class AddRemoveMenuWidget extends StatelessWidget {
  late bool deleteFlag;
  late bool isManager; //是否是有权限
  late VoidCallback addPressed;
  late VoidCallback removePressed;
  late VoidCallback deletePressed;

  AddRemoveMenuWidget({
    required bool deleteFlag,
    required bool isManager,
    required VoidCallback addPressed,
    required VoidCallback removePressed,
    required VoidCallback deletePressed,
  }) {
    this.isManager = isManager;
    this.addPressed = addPressed;
    this.removePressed = removePressed;
    this.deleteFlag = deleteFlag;
    this.deletePressed = deletePressed;
  }

  @override
  Widget build(BuildContext context) {
    if (deleteFlag) {
      return TextButton(onPressed: deletePressed, child: Text("删除"));
    }
    if (isManager) {
      return Row(
        children: [
          IconButton(
            onPressed: removePressed,
            icon: Icon(
              Icons.remove,
              color: Color(0xff999999),
              size: 24,
            ),
          ),
          IconButton(
            onPressed: () {
              addPressed();
            },
            icon: Icon(
              Icons.add,
              color: Color(0xff999999),
              size: 24,
            ),
          )
        ],
      );
    } else {
      return IconButton(
        onPressed: () {
          addPressed();
        },
        icon: Icon(
          Icons.add,
          color: Color(0xff999999),
          size: 24,
        ),
      );
    }
  }
}
